package org.example;

import org.example.Enum.ActionEnum;
import org.example.Enum.Conditions;
import org.example.Enum.States;

import java.util.ArrayList;

/**
 * @program: B3_exper4
 * @description:
 * @create: 2023-11-05 10:47
 **/
public class StateMachine {
    private ArrayList<StateTranslation>stateTranslations;
    private States currentState;

    public StateMachine(States currentState){
        stateTranslations = new ArrayList<StateTranslation>();
        this.currentState = currentState;
    }

    public StateTranslation addTranslation(){
        StateTranslation stateTranslation = new StateTranslation();
        stateTranslations.add(stateTranslation);
        return stateTranslation;
    }

    public States getCurrentState() {
        return currentState;
    }

    public StateTranslation execute(ActionEnum action, Conditions conditions){
        for (StateTranslation translation : stateTranslations){
            if (translation.getCurrentState() == currentState   // 在当前状态下
                    && translation.getAction() == action        // 发生了当前动作
                    && (translation.getCondition() == conditions
                    || translation.getCondition() == null || conditions == null)   /* 满足前提条件, null表示无前提条件 */){
                translation.getEvent().handle(); // 执行相应的动作
                currentState = translation.getNextState(); // 状态转换至下一个状态
                return translation;
            }
        }
        return null;
    }
}
